using System;
using System.Web.UI;
using NorthwindTableAdapters;

public partial class DataHandler : Page {
    int start, limit;
    private string sortExpression;

    private CategoriesTableAdapter _categories;
    public CategoriesTableAdapter Categories { get { return _categories ?? (_categories = new CategoriesTableAdapter()); } }
    private ProductsTableAdapter _products;
    public ProductsTableAdapter Products { get { return _products ?? (_products = new ProductsTableAdapter()); } }
    private SuppliersTableAdapter _suppliers;
    public SuppliersTableAdapter Suppliers { get { return _suppliers ?? (_suppliers = new SuppliersTableAdapter()); } }

    protected void Page_Load(object sender, EventArgs e) {
        Response.Clear();
        string action = Request["action"];
        switch (action) {
            case "ListProducts":   ListProducts(); break;
            case "InsertProduct":  InsertProduct(); break;
            case "UpdateProduct":  UpdateProduct(); break;
            case "DeleteProduct":  DeleteProduct(); break;
            
            case "ListCategories": ListCategories(); break;
            case "InsertCategory": InsertCategory(); break;
            case "UpdateCategory": UpdateCategory(); break;
            case "DeleteCategory": DeleteCategory(); break;
            
            case "ListSuppliers":  ListSuppliers(); break;
            case "InsertSupplier": InsertSupplier(); break;
            case "UpdateSupplier": UpdateSupplier(); break;
            case "DeleteSupplier": DeleteSupplier(); break;
        }
        Response.End();
    }

    // Products
    private void ListProducts() {
        if (!Int32.TryParse(Request["start"], out start)) start = 0;
        if (!Int32.TryParse(Request["limit"], out limit)) limit = 30;
        string sort = Request["sort"] ?? "ProductName";
        if (sort == "SupplierName") sort = "CompanyName"; // quick fix for incorrect sql in dbo.GetProductsPagedAndSorted sp
        string dir = Request["dir"] ?? "ASC";
        sortExpression = sort + " " + dir;

        int? count = Products.TotalNumberOfProducts();
        Northwind.ProductsDataTable products = Products.GetProductsPagedAndSorted(sortExpression, start, limit);
        Response.Write("{totalCount:" + count + ", results:" + JsonSerializer.Serialize(products) + "}");
    }
    private void InsertProduct() {
        int? prodId = Products.InsertProduct(
            Request["ProductName"],   
            Convert.ToInt32(Request["hSupplierID"]), 
            Convert.ToInt32(Request["hCategoryID"]),   
            Request["QuantityPerUnit"],   
            Convert.ToInt32(Request["UnitPrice"]),   
            Convert.ToInt16(Request["UnitsInStock"]),   
            Convert.ToInt16(Request["UnitsOnOrder"]),   
            Convert.ToInt16(Request["ReorderLevel"]),   
            Request["Discontinued"] == "on" ? true : false   
        );
        Response.Write("{success:true,ProductID:" + prodId + "}");
    }
    private void UpdateProduct() {
        Products.Update(
            Request["ProductName"],
            Convert.ToInt32(Request["hSupplierID"]),
            Convert.ToInt32(Request["hCategoryID"]),
            Request["QuantityPerUnit"],
            Convert.ToDecimal(Request["UnitPrice"]),
            Convert.ToInt16(Request["UnitsInStock"]),
            Convert.ToInt16(Request["UnitsOnOrder"]),
            Convert.ToInt16(Request["ReorderLevel"]),
            Request["Discontinued"] == "on" ? true : false,
            Convert.ToInt32(Request["ProductID"])
        );
        Response.Write("{success:true,ProductID:" + Request["ProductID"] + "}");
    }
    private void DeleteProduct() {
        Products.Delete(Convert.ToInt32(Request["ProductID"]));
        Response.Write("{success:true,ProductID:" + Request["ProductID"] + "}");
    }

    // Categories
    private void ListCategories() {
        int? count = Categories.TotalNumberOfCategories();
        Northwind.CategoriesDataTable cats = Categories.GetCategories();
        Response.Write("{totalCount:" + count + ", results:" + JsonSerializer.Serialize(cats) + "}");
    }
    private void InsertCategory() {
        int catId = Categories.InsertCategory(Request["CategoryName"], Request["Description"]);
        Response.Write("{success:true,CategoryID:" + catId + "}");
    }
    private void UpdateCategory() {
        Categories.Update(Request["CategoryName"], Request["Description"], Convert.ToInt32(Request["CategoryID"]));
        Response.Write("{success:true,CategoryID:" + Request["CategoryID"] + "}");
    }
    private void DeleteCategory() {
        Categories.Delete(Convert.ToInt32(Request["CategoryID"]));
        Response.Write("{success:true,CategoryID:" + Request["CategoryID"] + "}");
    }

    // Suppliers
    private void ListSuppliers() {
        int? count = Suppliers.TotalNumberOfSuppliers();
        Northwind.SuppliersDataTable suppliers = Suppliers.GetSuppliers();
        Response.Write("{totalCount:" + count + ", results:" + JsonSerializer.Serialize(suppliers) + "}");
    }
    private void InsertSupplier() {
        int supId = Suppliers.InsertSupplier(
            Request["CompanyName"],
            Request["ContactName"],
            Request["ContactTitle"],
            Request["Address"],
            Request["City"],
            Request["Region"],
            Request["PostalCode"],
            Request["Country"],
            Request["Phone"],
            Request["Fax"],
            Request["HomePage"]
        );
        Response.Write("{success:true,SupplierID:" + supId + "}");
    }
    private void UpdateSupplier() {
        Suppliers.Update(
            Request["CompanyName"],
            Request["ContactName"],
            Request["ContactTitle"],
            Request["Address"],
            Request["City"],
            Request["Region"],
            Request["PostalCode"],
            Request["Country"],
            Request["Phone"],
            Request["Fax"],
            Request["HomePage"],
            Convert.ToInt32(Request["SupplierID"])
        );
        Response.Write("{success:true,SupplierID:" + Request["SupplierID"] + "}");
    }
    private void DeleteSupplier() {
        Suppliers.Delete(Convert.ToInt32(Request["SupplierID"]));
        Response.Write("{success:true,SupplierID:" + Request["SupplierID"] + "}");
    }
}